import 'package:flutter/material.dart';
import 'package:flutter_douban/config/app_colors.dart';
import 'package:flutter_douban/config/app_config.dart';
import 'package:flutter_douban/config/sqflite/user_db_provider.dart';
import 'package:flutter_douban/main_page/me/view/user_config_top_view.dart';
import 'package:flutter_douban/main_page/me/view/user_config_view.dart';
import 'package:flutter_douban/tool_views/app_dialog.dart';
import 'package:flutter_douban/tool_views/back_nav_btn.dart';
import 'package:flutter_douban/tool_views/ios_loading_dialog.dart';
import 'package:flutter_douban/tool_views/nav_title_page.dart';
import 'package:shared_preferences/shared_preferences.dart';

class UserConfigPage extends StatefulWidget {
  const UserConfigPage({Key? key}) : super(key: key);

  @override
  _UserConfigPageState createState() => _UserConfigPageState();
}

class _UserConfigPageState extends State<UserConfigPage> {
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  late TextEditingController _nickTextEditingController;
  late TextEditingController _jianTextEditingController;
  String _nickStr = '';
  String _jianStr = '';

  FocusNode blankNode = FocusNode();

  // final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  List _list = [
    '性别',
    '生日',
    '职业',
    '家乡',
  ];
  List _valueList = [];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _getData();
    _nickTextEditingController = TextEditingController();
    _jianTextEditingController = TextEditingController();
    _nickTextEditingController.addListener(() {
      setState(() {
        _nickStr = _nickTextEditingController.text;
      });
    });
    _jianTextEditingController.addListener(() {
      setState(() {
        _jianStr = _jianTextEditingController.text;
      });
    });
  }

  /// 获取数据
  Future<void> _getData() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String? numberId = prefs.getString(AppConfig.numberId);
    UserDbProvider userDbProvider = new UserDbProvider();
    List<Map<String, dynamic>> maps = [];
    userDbProvider.getUserData(numberId!).then((value) => {
          maps = value,
          print(maps),

          /// [{phoneNum: 13161138626, codeNum: 123456, nickName: 木子雨廷, sex: 男,
          /// birthday: 1993年06月06日, profession: IT/互联网,
          /// hometown: 河北省衡水市景县, signature: 我会做很多好吃的，快来和我交友吧。}]
          setState(() {
            /// 昵称赋值
            _nickTextEditingController.text = maps[0]['nickName'];

            /// 签名
            _jianTextEditingController.text = maps[0]['signature'];
            _valueList.add(maps[0]['sex']);
            _valueList.add(maps[0]['birthday']);
            _valueList.add(maps[0]['profession']);
            _valueList.add(maps[0]['hometown']);
          }),
        });
  }

  /// 保存按钮
  Future<void> _saveMethoed() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String? numberId = prefs.getString(
      AppConfig.numberId,
    );
    UserDbProvider userDbProvider = new UserDbProvider();
    userDbProvider
        .update(numberId!, _nickStr, _valueList[0], _valueList[1],
            _valueList[2], _valueList[3], _jianStr)
        .then((value) => {
              Loading.show(context),
              Future.delayed(const Duration(milliseconds: 1000), () {
                Loading.hide(context);
                AppDialog.showText(context, title: '保存成功');

                /// 返回登录
                Navigator.pop(context);
              }),
            });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _nickTextEditingController.dispose();
  }

  void didSelectMethod(String string) {
    if (string == '性别') {
      AppDialog.showSinglePickerModal(context,
          title: '',
          data: ['男', '女', '保密'],
          leftText: '选择性别',
          onCancel: () {}, onConfirm: (List values) {
        setState(() {
          _valueList.removeAt(0);
          _valueList.insert(0, values[0]);
        });
      }, scaffoldKey: _scaffoldKey);
    } else if (string == '生日') {
      AppDialog.showPickerDateTimeRoundBg(context, title: '', onCancel: () {},
          onConfirm: (String values) {
        setState(() {
          _valueList.removeAt(1);
          _valueList.insert(1, values);
        });
      }, scaffoldKey: _scaffoldKey);
    } else if (string == '职业') {
      AppDialog.showSinglePickerModal(context,
          title: '',
          leftText: '选择职业',
          data: [
            '全职主妇',
            '学生',
            '私企员工',
            '国企员工',
            '教师',
            '医生',
            '公务员',
            'IT/互联网',
            '营养师',
            '职业厨师',
            '律师',
            '会计',
            '翻译',
            '音乐人',
            '演员',
            '个体商人',
            '其他'
          ],
          onCancel: () {}, onConfirm: (List values) {
        setState(() {
          _valueList.removeAt(2);
          _valueList.insert(2, values[0]);
        });
      }, scaffoldKey: _scaffoldKey);
    } else if (string == '家乡') {
      // Navigator.of(context)
      //     .push(MaterialPageRoute(builder: (_) {
      //   return AddressPickerPage();
      // }));

      AppDialog.showAppAddressPicker(
        context,
        titleStr: '',
        leftText: '选择地址',
        onCancel: () {},
        onConfirm: (String values) {
          setState(() {
            _valueList.removeAt(3);
            _valueList.insert(3, values);
          });
        },
      );
    }
  }

  /// 展示地理位置
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        key: _scaffoldKey,
        appBar: AppBar(
            title: NavTitlePage(
              titleStr: '个人资料',
            ),
            leading: BackNavBtn(),
            actions: [
              FlatButton(
                  padding: EdgeInsets.all(0),
                  onPressed: _saveMethoed,
                  child: Container(
                    width: 50,
                    height: 26,
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      color: AppColors.yellow,
                      borderRadius: BorderRadius.circular(13),
                    ),
                    child: Text(
                      '保存',
                      style: TextStyle(fontSize: 12, color: AppColors.black),
                    ),
                  ))
            ]),
        body: GestureDetector(
          onTap: () {
            FocusScope.of(context).requestFocus(blankNode);
          },
          child: Container(
            color: Colors.white,
            child: ListView.builder(
                itemCount: _list.length + 3,
                // shrinkWrap: true, //增加
                itemBuilder: (BuildContext context, int index) {
                  if (index == 0) {
                    return UserConfigTopView();
                  } else if (index == 1) {
                    return _nickNameTextFiled(
                        '昵称', '你可以起一个不超过16个字的名字', _nickTextEditingController);
                  } else if (index == _list.length + 2) {
                    return _nickNameTextFiled(
                        '签名', '有趣的简介会吸引更多关注哦~', _jianTextEditingController);
                  } else {
                    return UserConfigView(
                      string: _list[index - 2],
                      desStr: _valueList[index - 2],
                      method: didSelectMethod,
                    );
                  }
                }),
          ),
        ));
  }

  Widget _nickNameTextFiled(String title, String hintText,
      TextEditingController textEditingController) {
    return Container(
      height: 55,
      padding: EdgeInsets.only(left: 15, right: 15),
      color: Colors.white,
      child: Column(
        children: [
          Row(
            children: [
              Text(
                title + '         ',
                style: TextStyle(
                  fontSize: 14,
                  color: Colors.black,
                  decorationColor: Colors.black45,
                ),
              ),
              Container(
                height: 54,
                width: MediaQuery.of(context).size.width - 100,
                color: Colors.white,
                alignment: Alignment.center,
                child: TextField(
                  autofocus: false,
                  style: TextStyle(fontSize: 14),
                  keyboardType: TextInputType.text,
                  controller: textEditingController,
                  cursorColor: AppColors.yellow,
                  decoration: InputDecoration.collapsed(
                      hintText: hintText,
                      hintStyle:
                          TextStyle(fontSize: 13, color: Colors.black26)),
                ),
              )
            ],
          ),
          Container(
            color: AppColors.line,
            height: 1,
          )
        ],
      ),
    );
  }
}
